package com.qcy.jwtdemo.filters;




import com.qcy.jwtdemo.config.JwtEncoder;
import com.qcy.jwtdemo.filters.threadLocalUtil.ThreadLocalUtils;
import com.qcy.jwtdemo.pojo.UserPrinciple;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;

import javax.servlet.*;
import javax.servlet.http.HttpServletRequest;
import java.io.IOException;


@Slf4j
@Component
public class AuthenticationFilter implements Filter {

    @Autowired
    private JwtEncoder<UserPrinciple> jwtEncoder;
    @Override
    public void init(FilterConfig filterConfig) throws ServletException {
        Filter.super.init(filterConfig);
    }

    @Override
    public void doFilter(ServletRequest servletRequest, ServletResponse servletResponse, FilterChain filterChain) throws IOException, ServletException {
        log.debug("请求进入过滤器");
        log.debug("当前线程是={}",Thread.currentThread().getName());
        if (servletRequest instanceof HttpServletRequest){
            //获取请求头中的 jwt
            HttpServletRequest req = (HttpServletRequest) servletRequest;
            String jwt = req.getHeader("Authorization");
            try {
                UserPrinciple userPrinciple = jwtEncoder.getLoginFromToken(jwt, UserPrinciple.class);
                ThreadLocalUtils.setValue(userPrinciple);
            } catch (Exception e) {
                throw new RuntimeException(e);
            }
        }

        //调用过滤链对象 将请求和相应向后调用
        filterChain.doFilter(servletRequest,servletResponse);

        //清空本次请求线程数据
        ThreadLocalUtils.remove();
        log.debug("请求结束！");

    }

    @Override
    public void destroy() {
        Filter.super.destroy();
    }
}
